import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/book_collect_data_manager.dart';
import 'package:flutter_reader/dao/bookinfo_data_manager.dart';
import 'package:flutter_reader/model/book/book_history_model.dart';
import 'package:flutter_reader/model/book_history_model/book_history_model.dart';
import 'package:flutter_reader/new/entity_novel_info.dart';
import 'package:flutter_reader/new/manager_router.dart';
import 'package:flutter_reader/pages/category/category_page.dart';
import 'package:flutter_reader/pages/read_book/book_content.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/pages/read_book/novel_book_reader_view.dart';
import 'package:flutter_reader/provider/book_his_provider.dart';
import 'package:flutter_reader/tools/colors.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:provider/provider.dart';

class BookHistoryPage extends StatefulWidget {
  BookHistoryPage({Key key}) : super(key: key);

  @override
  _BookHistoryPageState createState() {
    return _BookHistoryPageState();
  }
}

class _BookHistoryPageState extends State<BookHistoryPage> {
  bool hasData = false;


  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    Provider.of<BookHisProvider>(context).getBookList();

    if (Provider.of<BookHisProvider>(context).count > 0) {
      hasData = true;
    }

    final List<BookHis> books = Provider.of<BookHisProvider>(context).allBooks;

    final items = List<BookListItem>.generate(Provider.of<BookHisProvider>(context).count, (i) => BookListItem(bookHis: books[i],));

    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        return Slidable(
          key: ValueKey(index),
          actionPane: SlidableDrawerActionPane(),
          secondaryActions: <Widget>[
            IconSlideAction(
              caption: '删除',
              color: Colors.red,
              icon: Icons.delete,
              onTap: (){
                Provider.of<BookHisProvider>(context, listen: false).deleteBook(context, books[index]);
              },
            ),
          ],
          child: items[index],
        );
      },
    );
  }

}

class BookList extends StatefulWidget {
  final List<BookHis> books;
  BookList({Key key, this.books}) : super(key: key);

  @override
  _BookListState createState() {
    return _BookListState();
  }
}

class _BookListState extends State<BookList> {

  List<BookListItem> items;
  @override
  void initState() {
    debugPrint("页面初始化");
    items = widget.books.map((book) => BookListItem(
      bookHis: book,
    )).toList();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index){
          return Container(
            height: 1.27*ScreenUtil().setWidth(280),
            child: Dismissible(
              key: Key("key_$index"),
              onDismissed: (DismissDirection direction){
                setState(() {
                  items.removeAt(index);
                });
              },
              child: items[index],
            ),
          );
        });
  }
}

class BookListItem extends StatelessWidget {
  final BookHis bookHis;

  BookListItem({@required this.bookHis});

  @override
  Widget build(BuildContext context) {

    return InkWell(
      onTap: () {
        print('1');
      },
      child: Container(
        child: Row(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                boxShadow: <BoxShadow>[
                  new BoxShadow(
                    color: Colors.black26,
                    blurRadius: 5.0,
                    spreadRadius: 1.0,
                    offset: Offset(-2.0, 2.0),
                  ),
                ],
              ),
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(40),
                  ScreenUtil().setHeight(50),
                  ScreenUtil().setWidth(20),
                  ScreenUtil().setHeight(0)),
              child: Image(
                width: ScreenUtil().setWidth(280),
                height: 1.27*ScreenUtil().setWidth(280),
                image: NetworkImage(bookHis.bookImage),
                fit: BoxFit.fill,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(40)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                    width: ScreenUtil().setWidth(700),
                    height: ScreenUtil().setHeight(100),
                    child:  Text(
                      bookHis.bookName,
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(50),
                          fontWeight: FontWeight.w500
                      ),),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(700),
                    child: Text(
                      '阅读至  第${(bookHis.chaName).toString()}章',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil().setSp(40)
                      ),
                    ),
                  ),
                  Container(
                    height: ScreenUtil().setHeight(180),
                    padding: EdgeInsets.only(top: ScreenUtil().setHeight(80)),
                    child: SizedBox(
                      child: RaisedButton(
                        color: Colors.white,
                        padding: EdgeInsets.all(0),
                        shape: new RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(18.0)),
                        ),
                        onPressed: (){
                          NovelBookInfo currentBookInfo = NovelBookInfo()
                            ..bookId = bookHis.bookId
                            ..cover = bookHis.bookImage
                            ..title = bookHis.bookName
                            ..currentChapterIndex = int.parse(bookHis.chaName);

                          APPRouter.instance.route(
                              NovelBookReaderView.buildIntent(
                                  context,
                                  currentBookInfo));
                        },
                        textColor: Colors.white,
                        child: Container(
                          width: ScreenUtil().setWidth(600),
                          height: ScreenUtil().setHeight(180),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(Radius.circular(10.0))
                          ),
                          padding: EdgeInsets.all(0),
                          child:  Container(
                            child: Center(
                              child: Text(
                                  '继续阅读',
                                  style: TextStyle(fontSize: ScreenUtil().setSp(40),
                                      color: Colors.black54)
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}


/*
Dismissible(
          key: Key(index.toString()),
          onDismissed: (direction) {
            Provider.of<BookHisProvider>(context, listen: false).deleteBook(context, books[index]);
          },
          background: Container(color: Colors.red),
          child: items[index],
        );
 */
/*
Container(
      child: Consumer<BookHisProvider>(
        builder: (context, books, _) => hasData
            ? BookList(
          books: books.allBooks.toList(),
        )
            : Center(
          child: Text(
            '暂无书籍',
            style: TextStyle(
              fontSize: ScreenUtil().setSp(50),
            ),
          ),
        ),
      ),
    );
 */

/*
ListView.builder(
        itemCount: reBooks.length,
        itemBuilder: (context, index){
          return Dismissible(
            key: ValueKey(index),
            onDismissed: (_){
              setState(() {
                reBooks.clear();
              });
            },
            movementDuration: Duration(milliseconds: 100),
            child: BookListItem(
              bookHis: reBooks[index],
            ),
          );
        })
 */